package com.sinohb.autonomousdriving_test;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.hb.sq3d.Viewer3D;
import com.hb.sq3d.vos.ModelArg;

import java.util.ArrayList;
import java.util.List;

public class FloatingViewService extends Service {
    private WindowManager windowManager;
    private View floatingHandleBtn, floatingViewer3D;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

		/** simulate call native interface before JNI_Load success!*/
        List<ModelArg> models = new ArrayList<>();
        ModelArg car = new ModelArg(1, 0, new PointF(-4.0f, 15.0f), 0);
        models.add(car);
        Viewer3D.setComingModels(models, System.currentTimeMillis(), 0);

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        floatingViewer3D = LayoutInflater.from(this).inflate(R.layout.floating_viewer3d, null);

        floatingHandleBtn = LayoutInflater.from(this).inflate(R.layout.floating_btn, null);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.BOTTOM | Gravity.END;
        params.x = 0;
        params.y = 0;
        windowManager.addView(floatingHandleBtn, params);

        params.gravity = Gravity.TOP | Gravity.START;
        windowManager.addView(floatingViewer3D, params);

        floatingHandleBtn.findViewById(R.id.btn_show_3d).setOnClickListener(v -> {
            Viewer3D.setVisible(floatingViewer3D, true);
        });
        floatingHandleBtn.findViewById(R.id.btn_hide_3d).setOnClickListener(v -> {
            Viewer3D.setVisible(floatingViewer3D, false);
        });

        Viewer3D.setView3DInitCompletedListener(() -> {
            Log.i("FloatingView", "View3D has already init Completed!!!!!!");
        });

        floatingHandleBtn.findViewById(R.id.btn_stop_service).setOnClickListener(v -> {
            stopSelf();
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("FloatingViewService", "FloatingViewService::onDestroy");
//        if (floatingViewer3D != null) {
//            windowManager.removeView(floatingHandleBtn);
//            windowManager.removeView(floatingViewer3D);
//        }
    }
}